package cn.edu.sdju.fengguoyu;

import cn.edu.sdju.fengguoyu.proto.*;
import io.grpc.ManagedChannel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;

@Service
public class UserService {
    private static int idCounter = 1;
    HashMap<Integer, UserStatus> idStatusMap = new HashMap<>();
    public HashMap<Integer, Integer> userServiceMap = new HashMap<>();
    @Autowired
    ObserverConnectionsPool observerConnectionsPool;
    public int registerUser(UserInfo info) {
        int id = idCounter++;
        idStatusMap.put(id, UserStatus.newBuilder().build());
        for (ManagedChannel channel: observerConnectionsPool.observerChannels.values()
        ) {
            ObserverMessageBroadcastGrpc.ObserverMessageBroadcastBlockingStub stub = ObserverMessageBroadcastGrpc.newBlockingStub(channel);
            stub.sendNewUserMessage(NewUserMessage.newBuilder().setId(id).setIpAddress(info.getIpAddress()).build());
        }
        return id;
    }

    public UserStatus getUserStatusById(int id) {
        return idStatusMap.get(id);
    }
    public void updateUserStatusById(UpdateUserStatusRequest req) {
        idStatusMap.put(req.getId(), req.getNewStatus());
    }

    public void unRegisterUser(UserInfo info) {
        for (ManagedChannel channel: observerConnectionsPool.observerChannels.values()
        ) {
            ObserverMessageBroadcastGrpc.ObserverMessageBroadcastBlockingStub stub = ObserverMessageBroadcastGrpc.newBlockingStub(channel);
            stub.sendUserLeaveMessage(UserLeaveMessage.newBuilder().setId(info.getId()).build());
        }
    }

}
